//
//  NYSearchViewController.m
//  Nooryes
//
//  Created by baken on 2020/3/10.
//  Copyright © 2020 MyApp. All rights reserved.
//

#import "NYSearchViewController.h"
#import "NYSearchViewModel.h"
#import "NYTopicListModel.h"
#import "NYTopicListTableViewCell.h"
#import "NYTopicArticlesViewController.h"
#import "NYSearchResultViewController.h"
#import "TopicCategoryModel.h"
#import "NYTitleViewSearchBar.h"

#import "NYTopicCategoryModel.h"
#import "NSString+dynamicSize.h"
#import "NYAlertView.h"
#import "UINavigationController+FDFullscreenPopGesture.h"

@interface NYSearchViewController ()
@property (nonatomic,strong) NYSearchViewModel *searchVM;
@property (nonatomic,strong) NYTitleViewSearchBar *searchBar;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *historyHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *categoryHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topicListHeight;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIView *categoryView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UIView *historyView;

@property (nonatomic, strong) NSMutableArray *historyArray;

@end

@implementation NYSearchViewController

-(NYSearchViewModel *)searchVM{
    if (!_searchVM) {
        _searchVM = [NYSearchViewModel new];
    }
    return _searchVM;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = nil;
    
    UIButton *cancelButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 23)];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:UIColorFromRGB(0x888888) forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(clickCancel) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
    
    
    NYTitleViewSearchBar *titleView = [[NYTitleViewSearchBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth-100, 30)];
    self.searchBar = titleView;
    self.navigationItem.titleView = titleView;
    titleView.searchBlock = ^(NSString * text) {
        [self onSearch:text];
    };
    
    
    [self.searchVM getHotCategoryListWithCompletionHandle:^(NSError *error) {
        if (!error) {
            
            [self addTopicButton];
        }
    }];
    self.tableView.rowHeight = kTopicRowHeight;
    [self.searchVM getHotTopicListWithCompletionHandle:^(NSError *error) {
        if (!error) {
            
            [self.tableView reloadData];
            [self.topicListHeight setConstant:self.searchVM.tableViewHeight];
        }
    }];
    
    
    
    
    //    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
    //          [self.topicVM getMoreDataCompletionHandle:^(NSError *error) {
    //              [self.tableview reloadData];
    //              [self.tableview.mj_footer endRefreshing];
    //          }];
    //
    //      }];
    //
    
    
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"searchList"];
    [self.historyArray addObjectsFromArray:array];
    [self setupHistoryView:self.historyArray];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upList:) name:@"searchListChange" object:nil];
    
    
}
-(void)upList:(NSNotification *)notify{
    [self.historyArray setArray:notify.object];
    [self setupHistoryView:self.historyArray];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void)clickCancel{
    [self.searchBar.searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - saerch
- (void)onSearch:(NSString *)text {
    NSString *str = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (str.length>0) {
        NSMutableArray *newArray = [self.historyArray mutableCopy];
        /***  每搜索一次   就会存放一次到历史记录，但不存重复的*/
        [self.historyArray enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([text isEqualToString:obj]) {
                [newArray removeObject:obj];
                *stop = YES;
            }
        }];
        [newArray insertObject:text atIndex:0];
        [self setupHistoryView:newArray];
        [[NSUserDefaults standardUserDefaults] setObject:newArray forKey:@"searchList"];
        self.historyArray = newArray;
        NYSearchResultViewController *resultVC = [[NYSearchResultViewController alloc] initWithNibName:@"NYSearchResultViewController" bundle:nil];
        resultVC.keys = text;
        [resultVC.preSearchArray addObjectsFromArray:newArray];
        [self.navigationController pushViewController:resultVC animated:YES];
    } else {
        NYAlertView *alert = [NYAlertView sharedAlertView];
        alert.title = @"请输入要查询的内容";
        [alert showAlert:^{}];
    }
}


//设置历史搜索部分
-(void)setupHistoryView:(NSMutableArray *)array{
    [self addButtonWithCityArray:array ];
}


- (IBAction)deleteHistory:(id)sender {
    [self.historyArray removeAllObjects];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"searchList"];
    for (UIView *view in self.historyView.subviews) {
        [view removeFromSuperview];
    }
    [self.historyHeight setConstant:0];
}

#pragma mark - button创建方法 -

//循环创建Button
-(void)addButtonWithCityArray:(NSArray *)arr {
    if (self.historyView.frame.size.height>0) {
        for (UIView *view in self.historyView.subviews) {
            [view removeFromSuperview];
        }
    }
    CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    CGFloat h = 0;
    int tag = 0;
    
    CGFloat viewWidth = kScreenWidth - 24;
    
    UIView *buttonView1 = [[UIView alloc] init];
    UIView *buttonView2 = [[UIView alloc] init];
    UIView *buttonView3 = [[UIView alloc] init];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        button.backgroundColor = [UIColor clearColor];
        
        //设置圆角
        button.layer.cornerRadius = 15;//2.0是圆角的弧度，根据需求自己更改
        button.layer.borderColor =[UIColor lightGrayColor].CGColor;//设置边框颜色
        button.layer.borderWidth = 0.5f;//设置边框颜色
        
        [button addTarget:self action:@selector(historyClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        
        CGFloat length = [arr[i] dynamicWidthWithFontSize:12 andCGSize:CGSizeMake(viewWidth, MAXFLOAT) andLineSpace:0].width;
        //为button赋值
        [button setTitle:arr[i] forState:UIControlStateNormal];
        
        //当button的位置超出屏幕边缘时换行  只是button所在父视图的宽度
        if(10 + w + length + 35  > viewWidth){
            w = 0; //换行时将w置为0
            h = h + 40;//距离父视图也变化
            tag ++;
            button.frame = CGRectMake(12 + w, 0, length + 35, 30);//重设button的frame
        }else{
            button.frame = CGRectMake(12 + w, 0, length + 35 ,30);
        }
        w = button.frame.size.width + button.frame.origin.x;
        
        switch (tag) {
            case 0:
                [buttonView1 addSubview:button];
                buttonView1.frame = CGRectMake(0 , h, w + length + 35, 30);
                break;
            case 1:
                [buttonView2 addSubview:button];
                buttonView2.frame = CGRectMake(0 , h, w + length + 35, 30);
                break;
            case 2:
                [buttonView3 addSubview:button];
                buttonView3.frame = CGRectMake(0 , h, w + length + 35, 30);
            default:
                break;
        }
    }
    [self.historyView addSubview:buttonView1];
    [self.historyView addSubview:buttonView2];
    [self.historyView addSubview:buttonView3];
    [self.historyHeight setConstant:h + 30];
    
}

//循环创建Button
-(void)addTopicButton{
    CGFloat w = kScreenWidth * 0.5;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    CGFloat h = 30;
    [self.searchVM.cateroryArray enumerateObjectsUsingBlock:^(TopicCategoryModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(w * (idx %2), (idx / 2) * h, w, h)];
        button.titleLabel.font = [UIFont systemFontOfSize:13];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 30, 0, 0);
        [button addTarget:self action:@selector(topicClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:UIColorFromRGB(0x000000) forState:UIControlStateNormal];
        [button setTitle:obj.name forState:UIControlStateNormal];
        button.tag = idx;
        [self.categoryView addSubview:button];
    }];
    
}


#pragma mark UITableView
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TopicListModel *model = [self.searchVM.topicArray objectAtIndex:indexPath.row];
    NYTopicListTableViewCell *cell = [NYTopicListTableViewCell cellWithTableView:tableView];
    cell.model = model;
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TopicListModel *model = [self.searchVM.topicArray objectAtIndex:indexPath.row];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TopicStoryboard" bundle:nil];
    NYTopicArticlesViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYTopicArticlesViewController"];
    detailVC.topicID = model.talkid;
    [self.navigationController pushViewController:detailVC animated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchVM.topicArray.count;
}



- (void)historyClick:(UIButton *)btn{
    NYSearchResultViewController *resultVC = [[NYSearchResultViewController alloc] initWithNibName:@"NYSearchResultViewController" bundle:nil];
    resultVC.keys = btn.titleLabel.text;
    [self.navigationController pushViewController:resultVC animated:YES];
}



- (void)topicClick:(UIButton *)btn{
    TopicCategoryModel *model = [self.searchVM.cateroryArray objectAtIndex:btn.tag];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TopicStoryboard" bundle:nil];
    NYTopicArticlesViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYTopicArticlesViewController"];
    detailVC.topicID = model.talkid;
    [self.navigationController pushViewController:detailVC animated:YES];
}


-(NSMutableArray *)historyArray{
    if (!_historyArray) {
        _historyArray = [NSMutableArray array];
    }
    return _historyArray;
}


@end
